package com.lee.commonerror.code.lock;

import com.lee.commonerror.common.annotation.Right;
import com.lee.commonerror.common.annotation.Wrong;
import lombok.Data;
import lombok.Getter;

import java.util.stream.IntStream;

/**
 *
 *
 * @author ：liylw
 * @date ：Created in 2021/4/12 16:59
 */
@Wrong("锁的级别导致错误")
public class DataWrong {

    @Getter
    private static int counter = 0;

    private static final Object locker = new Object();

    public static int reset() {
        counter = 0;
        return counter;
    }

    /**
     * 锁的是实例,counter是类属性
     */
    @Wrong("锁的是实例,counter是类属性")
    public synchronized void wrong() {
        counter++;
    }

    @Right
    public void right() {
        synchronized (locker) {
            counter++;
        }
    }


    public static void main(String[] args) {
        DataWrong.reset();
        IntStream.rangeClosed(1, 1_000_000).parallel().forEach(i -> new DataWrong().wrong());
        System.out.println(DataWrong.counter);

        DataWrong.reset();
        IntStream.rangeClosed(1, 1_000_000).parallel().forEach(i -> new DataWrong().right());
        System.out.println(DataWrong.counter);
    }
}
